#include <iostream>
#include <vector>
#include <map>
#include <string>
using namespace std;
// 测试链接 : https://leetcode.cn/problems/evaluate-division/

class Solution {
	map<string, string> fmp;
	map<string, double> val;

        string find(string &x)
        {
                if(x != fmp[x]){
                        string t = fmp[x];
                        fmp[x] = find(t);
                        val[x] *= val[t];
                }
                return fmp[x];
        }

        void unite(string &x, string &y, double v)
        {
                string fx = find(x), fy = find(y);
                if(fx != fy){
                        fmp[fx] = fy;
                        val[fx] = val[y] * v / val[x];
                }
        }

        double query(string &x, string &y)
        {
                string fx = find(x), fy = find(y);
                if(fx == "" || fy == ""){
                        return -1.0;
                }

                if(fx == fy){
                        return val[x] / val[y];
                }
                return -1.0;
        }

    public:
	vector<double> calcEquation(vector<vector<string>> &equations, vector<double> &values, vector<vector<string>> &queries)
	{
		for (int i = 0; i < equations.size(); i++) {
			for (auto &v : equations[i]) {
				fmp[v] = v;
                                val[v] = 1;
			}
		}

                for(int i = 0; i < equations.size(); i++){
                        string x = equations[i][0], y = equations[i][1];
                        double z = values[i];
                        unite(x, y, z);
                }

                vector<double> ans;
                for (int i = 0; i <queries.size(); i++) {
                        string x = queries[i][0], y = queries[i][1];
                        double z = query(x, y);
                        ans.push_back(z);
                }
                return ans;
	}
};

int main()
{
	vector<vector<string>> equations = { { "a", "b" }, { "b", "c" } };
	vector<double> values = { 2.0, 3.0 };
	vector<vector<string>> queries = { { "a", "c" }, { "b", "a" }, { "a", "e" }, { "a", "a" }, { "x", "x" } };
        vector<double> ans = Solution().calcEquation(equations, values, queries);
        for(auto v : ans){      
                cout << v << " ";
        }
        cout << endl;
	return 0;
}